package com.xing.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xing.reggie.common.R;
import com.xing.reggie.dto.DishDto;
import com.xing.reggie.entity.Category;
import com.xing.reggie.entity.Dish;
import com.xing.reggie.entity.DishFlavor;
import com.xing.reggie.service.CategoryService;
import com.xing.reggie.service.DishFlavorService;
import com.xing.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;
//
//    @Autowired
//    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> save(@RequestBody DishDto dishDto){
        //调用自定义新增方法
        dishService.savaWithFlavor(dishDto);
        //清理缓存所有信息
//        Set keys = redisTemplate.keys("key_*");
//        redisTemplate.delete(keys);
        //清理指定部分缓存信息
        String key = "dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
//        redisTemplate.delete(""+key);
        return R.success("新增菜品成功！");
    }

    /**
     * 菜品信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, String name){
        //分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null,Dish::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //根据条件查询
        dishService.page(pageInfo,queryWrapper);
        //拷贝数据
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item)->{
            DishDto dishDto = new DishDto();
            //拷贝
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId(); //拿到菜品分类Id
            //根据id得到分类对象
            Category category = categoryService.getById(categoryId);
            //根据分类对象得到分类名称
            String categoryName = category.getName();
            //将得到的分类名称写入dto中
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);

    }

    /**
     * 通过id查询菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Cacheable(value = "dishCache",key = "#id")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }


    /**
     * 修改菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto){
        //调用自定义修改方法
        dishService.updateWithFlavor(dishDto);
        //清理缓存所有信息
//        Set keys = redisTemplate.keys("key_*");
//        redisTemplate.delete(keys);
        //清理指定部分缓存信息
//        String key = "dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
//        redisTemplate.delete(""+key);
        return R.success("新增修改成功！");
    }

    /**
     * 删除菜品信息
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids){
    log.info("id:"+ids);
    //通过自定义方法删除两张表信息
        dishService.removeWithFlavor(ids);
        return R.success("删除菜品信息成功！");
    }

    /**
     * 根据条件id和提交状态值进行修改状态，0位停售，1为起售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> status(@PathVariable Integer status,@RequestParam List<Long> ids){
       log.info("status:"+status+",ids:"+ids);
        //条件构造器
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        //添加条件
        updateWrapper.set(Dish::getStatus,status);
        updateWrapper.in(Dish::getId,ids);
        //进行修改
        dishService.update(updateWrapper);
//        //清理缓存所有信息
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        return R.success("菜品状态修改成功！");
    }

    /**
     * 根据条件查询菜品信息
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "#dish.categoryId + '_' + #dish.status")
    public R<List<DishDto>> list(Dish dish){
//        List<DishDto> dishDtoList = null;
//        //先从Redis服务器中查找数据
//        //动态的构造key
//        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
//        //如果状态为0，清楚缓存
//        if (dish.getStatus() == 0){
//            Set keys = redisTemplate.keys("dish_*");
//            redisTemplate.delete(keys);
//        }
//        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
//        //如果存在，直接返回
//        if (dishDtoList != null) {
//            return R.success(dishDtoList);
//        }

        //构建条件查询
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //查询状态为1的菜品（起售）
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序查询
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询
        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item)->{
            //拷贝
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            //得到菜品ID
            Long id = item.getId();
            //通过id得到分类名称
            Category category = categoryService.getById(id);
            if (category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //通过id得到菜品口味
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId,id);
            List<DishFlavor> dishFlavors = dishFlavorService.list(wrapper);
           //设置口味
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        //如果不存在，查询数据库，并将数据缓存入Redis
//        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }


}
